package com.oocl.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VoUtil {

	public static <T> T translate(Class<T> targetClass, Object obj) {
		T t = null;
		Method[] methods = targetClass.getDeclaredMethods();
		try {
			t = targetClass.newInstance();
			for (Method method : methods) {
				String methodName = method.getName();
				if (methodName.startsWith("set")) {
					String getMethodName = methodName.replaceFirst("(set)",
							"get");
					Method setMethod = obj.getClass().getDeclaredMethod(
							getMethodName);
					Object value = setMethod.invoke(obj);
					if (setMethod.getReturnType().equals(Date.class)) {
						if(value!=null){
							value = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
							.format(value);
						}else{
							value="";
						}
					}
					method.invoke(t, value);
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return t;
	}

	public static <T, V> List<T> translateList(Class<T> targetClass,
			List<V> resources) {
		if (resources != null && resources.size() != 0) {
			List<T> list = new ArrayList<T>();
			for (V ot : resources) {
				T t = translate(targetClass, ot);
				list.add(t);
			}
			return list;
		} else {
			return null;
		}
	}
	
	
	public static Object copyWithoutNull(Object o,Object tagetObject) throws Exception{
		Method[] methods = o.getClass().getDeclaredMethods();
		
 		for(Method m:methods){
 			String methodName = m.getName();
			if (methodName.startsWith("get")) {
			   Object value =   m.invoke(o);
			   if(value!=null){
				  String SetmethodName = methodName.replaceFirst("(get)",
							"set");
				   Method setMethod = tagetObject.getClass().getDeclaredMethod(SetmethodName,m.getReturnType());
				   setMethod.invoke(tagetObject, value);
			   }
			}
			}
	
		
		
		
		return tagetObject;
	}

}
